import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { ApiService, JsonResult } from './api.service';
import { PageVo, GroupListVo, RoleGroupVo } from 'src/app/shared/models';

@Injectable({
  providedIn: 'root'
})
export class GroupService {

  constructor(
    private apiService: ApiService
  ) { }

  /**
  * 获取第三方库的列表和过滤信息
  * @param pageIndex 页面
  * @param pageSize 一页的数据
  * @param filter 过滤条件
  */
  getGroupPage(pageIndex: number = 1, pageSize: number = 10, filter: string): Observable<PageVo<GroupListVo>> {
    if (filter !== null && filter !== undefined && filter !== '') {
      if (filter.length > 1 && filter.length < 50) {
        const params = new HttpParams()
          .append('pageIndex', `${pageIndex}`)
          .append('pageSize', `${pageSize}`)
          .append('filter', filter);
        console.log('Janine===params==2==', params);
        return this.apiService.get('/group/all', { params })
          .pipe(
            map((jsonResult: JsonResult<PageVo<GroupListVo>>) => jsonResult.data)
          );
      }
    } else {
      const params = new HttpParams()
        .append('pageIndex', `${pageIndex}`)
        .append('pageSize', `${pageSize}`);
      console.log('Janine===params==3==', params);
      return this.apiService.get('/group/all', { params })
        .pipe(
          map((jsonResult: JsonResult<PageVo<GroupListVo>>) => jsonResult.data)
        );
    }
  }

  getRole(): Observable<PageVo<RoleGroupVo>> {
    return this.apiService.get('/role/select')
      .pipe(
        map((jsonResult: JsonResult<PageVo<RoleGroupVo>>) => jsonResult.data)
      );
  }

  saveGroup(groupName: string) {
    console.log('groupName', groupName);
    return this.apiService.put('/saveGroup', { 'groupName': groupName })
      .pipe(
        map((jsonResult: JsonResult<PageVo<GroupListVo>>) => jsonResult.data)
      );
  }

  getGroup() {
    return this.apiService.get('/group/select')
      .pipe(
        map((jsonResult: JsonResult<PageVo<GroupListVo>>) => jsonResult.data)
      );
  }
}
